package cn.xgx.exception.handle;


import cn.xgx.exception.MyValidateException;
import cn.xgx.result.ResponseData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import javax.validation.ConstraintViolationException;


@Slf4j
@ControllerAdvice
@ResponseBody
public class MyExceptionHandler {

    @ExceptionHandler
    public ResponseData myValidateException(MyValidateException e) {
        return ResponseData.error(e.getMessage());
    }

    /**
     * spring mvc在接收参数时，如果类型转换错误则会弹出此异常
     * 例如：某控制器的某个请求如下
     * public ResponseData hello(Integer number1, BigDecimal number2){
     * }
     * 如果传递过来的number1为a，则会出现下述异常
     */
    @ExceptionHandler
    public ResponseData methodArgumentTypeMismatchException(MethodArgumentTypeMismatchException e) {
        return ResponseData.validateError();
    }

    /**
     * json转换异常时出现
     * 例1：
     * @PostMapping("/testPost")
     * public ResponseData jsonTest(@Valid @RequestBody User user){
     * 如果没有传递user对象，则会出现该异常
     */
    @ExceptionHandler
    public ResponseData httpMessageNotReadableException(HttpMessageNotReadableException e) {
        return ResponseData.validateError();
    }

    @ExceptionHandler
    public ResponseData bindException(BindException e) {
        return ResponseData.validateError();
    }

    @ExceptionHandler(ConstraintViolationException.class)
    public ResponseData constraintViolationException(ConstraintViolationException e) {
        return ResponseData.validateError();
    }

    //spring mvc在接收参数时，如果无法接收到值出现此异常（如该值是必须的，或是不符合传输类型要求，导致无法接收到值）
    @ExceptionHandler
    public ResponseData missingServletRequestParameterException(MissingServletRequestParameterException e) {
        return ResponseData.validateError();
    }

    /**
     * 处理其他异常
     * @param e
     * @return
     */
    @ExceptionHandler(Throwable.class)
    public ResponseData unknownException(Throwable e) {
        return ResponseData.validateError();
    }
}
